package com.panicstyle.Gongdong;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.*;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class GongdongActivity extends ListActivity {
	TextView selection;
//	String[] items;
	String[] items={"怨듬룞�≪븘1", "怨듬룞�≪븘2", "怨듬룞�≪븘3"};
	
    private List<Map> arrayItems;
    
    private static class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private Bitmap mIcon1;
        private Bitmap mIcon2;
        List<Map> arrayItems;
        
        public EfficientAdapter(Context context, List<Map> data) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);

            // Icons bound to the rows.
            mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
            mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
            
            arrayItems = data;
        }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return arrayItems.size() ;
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return position;
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.list_item_rootview, null);

                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.title = (TextView) convertView.findViewById(R.id.title);

                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }
            HashMap item = new HashMap();
            String title = null;
            String code = null;
            item = (HashMap)arrayItems.get(position);
            title = (String)item.get("title");
            // Bind the data efficiently with the holder.
            holder.title.setText(title);

            return convertView;
        }

        static class ViewHolder {
            TextView title;
        }
    }
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);

        LoadData();
    }
    
    private void LoadData() {
        
        HttpClient httpClient;
    	HttpContext httpContext;
    	CookieStore cookieStore;
        
        GongdongApplication app = (GongdongApplication)getApplication();
        httpClient = app.httpClient;
        httpContext = app.httpContext;
        cookieStore = app.cookieStore;
        
        // Login
		Login login = new Login();
		
		ProgressDialog waitDialog = ProgressDialog.show(this, "", "로그인중입니다. 잠시 기다려주세요", true);
		
		if (!login.LoginTo(httpClient, httpContext, cookieStore, getBaseContext())) {
			waitDialog.dismiss();
			AlertDialog.Builder ab = null;
			ab = new AlertDialog.Builder( this );
			ab.setMessage( "로그인 정보가 설정되지 않았습니다. 설정 메뉴를 통해 로그인 정보를 설정하십시오.");
			ab.setPositiveButton(android.R.string.ok, null);
			ab.setTitle( "로그인 오류" );
			ab.show(); 
			return;
		}
		waitDialog.dismiss();
		
		arrayItems = getData(httpClient, httpContext);

        setListAdapter(new EfficientAdapter(this, arrayItems));
    }

    protected List getData(HttpClient httpClient, HttpContext httpContext) {		
		
		String url = "http://www.gongdong.or.kr/front";
		HttpRequest httpRequest = new HttpRequest();
		
		ProgressDialog waitDialog = ProgressDialog.show(this, "", "로딩중입니다. 잠시 기다려주세요", true);

        String result = httpRequest.requestGet(httpClient, httpContext, url);
        
        // Direct use of Pattern:
        String regex = "(<select name=\\\"community)(.|\\n)*?(</select>)";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); 
        Matcher m = p.matcher(result);
        String cafelist = "";
        if (m.find()) { // Find each match in turn; String can't do this.     
        	cafelist = m.group(0); // Access a submatch group; String can't do this. }        
        	System.out.println("m.find()");
        	System.out.println(cafelist);
        } else {
        	System.out.println("m.find() is FAIL");
        }

        // 
        HashMap item;
        List arrayItems = new ArrayList();

        p = Pattern.compile("(<option value=)(.|\\n)*?(</option>)", Pattern.CASE_INSENSITIVE); 
        m = p.matcher(cafelist);
        int i = 0;
        while (m.find()) { // Find each match in turn; String can't do this.     
            item = new HashMap();
            String option = m.group(0);
        	System.out.println(option);
         
	        Pattern p2 = Pattern.compile("(?<=value=\\\")(.|\\n)*?(?=\\\")", Pattern.CASE_INSENSITIVE); 
	        Matcher m2 = p2.matcher(option);
	        if (m2.find()) { // Find each match in turn; String can't do this.     
	//        	items.add(m.group(0)); // Access a submatch group; String can't do this. }
	        	String code = m2.group(0);
	        	System.out.println(code);
	            item.put("code", code);
	        } else {
	            item.put("code", "");
	        }

	        String title = option.replaceAll("<((.|\\n)*?)+>", "");
	        title = title.trim();
	        
            item.put("title", title);
            arrayItems.add( item );
        	
        	i++;
        }
		waitDialog.dismiss();

        return arrayItems;
    }

    public void onListItemClick(ListView parent, View v, int position, long id) {
        HashMap item = new HashMap();
        String title = null;
        String code = null;
        item = (HashMap)arrayItems.get(position);
        title = (String)item.get("title");
        code = (String)item.get("code");
        
        Intent intent = new Intent(this, BoardActivity.class);
        intent.putExtra("BOARD_TITLE", title);
        intent.putExtra("BOARD_CODE", code);
        startActivity(intent);    
    }
    
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        super.onCreateOptionsMenu(menu);  
          
        menu.add(0, 0, 0, "Setting");  
        menu.add(0, 1, 0, "About");  
          
        return true;  
    }  
      
    @Override  
    public boolean onOptionsItemSelected(MenuItem item) {  
        if (item.getItemId() == 0) {
            Intent intent = new Intent(this, SetView.class);
            startActivity(intent);
            return true;  
        } else if (item.getItemId() == 1) {
            Intent intent = new Intent(this, AboutView.class);
            startActivity(intent);    
            return true;  
        }   
        return false;  
    }
    
}